﻿/*
 * Created by SharpDevelop.
 * Date: 03.11.2011 г.
 * Time: 15:05 ч.
 * 
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.Serialization;
using System.Windows.Forms;

namespace CaesarCoder
{
	/// <summary>
	/// Description of Editor.
	/// </summary>
	public partial class Editor : Form
	{
		ConversionTable ct_orig;
		ConversionTable ct_edit;
		string ConfigDir = "";
		public bool CreateNew = false;
		
		public Editor(ConversionTable ct, string ConfigDir)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			if (ConfigDir != null) this.ConfigDir = ConfigDir;
			
			if (ct != null && ct.Table != null && ct.Table.Count > 0)
			{
				// we're editing an existing table
				this.CreateNew = false;
				this.ct_orig = ct;
				this.ct_edit = new ConversionTable(this.ct_orig);
			}
			else
			{
				// we're creating a new table
				this.CreateNew = true;
				this.ct_edit = new ConversionTable();
			}
		}
		
		void editor_loaded(object sender, EventArgs e)
		{
			//set the appropriate CellType of each column, so that the user can't enter invalid data
			this.Key.ValueType = typeof(byte);
			this.Value.ValueType = typeof(byte);
			
			if (this.CreateNew == true)
			{
				this.btnSave.Text = "Save As";
				this.btnRevert.Text = "Clear";
			} else {
				foreach (KeyValuePair<byte, byte> elem in this.ct_orig.Table)
				{
					dgvTable.Rows.Add(elem.Key, elem.Value);
				}
				if (this.ct_orig.Name != null) this.tbName.Text = this.ct_orig.Name;
				if (this.ct_orig.Description != null) this.tbDescription.Text = this.ct_orig.Description;
			}
		}
		
		void invalid_data_entered(object sender, DataGridViewDataErrorEventArgs e)
		{
			MessageBox.Show("The value you entered is invalid.\n\nPlease enter an integer between 0 and 255", "Invalid input", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		}
		
		void btnRevert_Click(object sender, EventArgs e)
		{
			if (this.CreateNew == true)
			{
				this.tbName.Text = "";
				this.tbDescription.Text = "";
				this.dgvTable.Rows.Clear();
			} else {
				this.tbName.Text = ct_orig.Name;
				this.tbDescription.Text = ct_orig.Description;
				this.dgvTable.Rows.Clear();
				foreach (KeyValuePair<byte, byte> elem in this.ct_orig.Table)
				{
					dgvTable.Rows.Add(elem.Key, elem.Value);
				}
			}
		}
		
		void BtnCancel_Click(object sender, EventArgs e)
		{
			// No need to do anything, btnCancel is set as CancelButton of this Form
		}
		
		void BtnSave_Click(object sender, EventArgs e)
		{
			// first remove all empty !new rows
			foreach (DataGridViewRow row in dgvTable.Rows)
			{
				if (!row.IsNewRow)
				{
					if ((row.Cells[0].Value == null) && (row.Cells[0].Value.ToString() == string.Empty) 
					    	&& (row.Cells[1].Value == null) && (row.Cells[1].Value.ToString() == string.Empty))
					{
						this.dgvTable.Rows.RemoveAt(row.Index);
					}
				}
			}
			
			bool duplicate_key = false; //indicates that some rows in the table have the same key
			bool duplicate_val = false;
			bool cell_empty = false;//indicates that a cell has been left empty
			int current_row_idx = 0;
			Dictionary<byte, byte> mod = new Dictionary<byte, byte>();
			try
			{
				foreach (DataGridViewRow row in dgvTable.Rows)
				{
					if (!row.IsNewRow) {
						if ((row.Cells[0].Value.ToString() == string.Empty) || (row.Cells[1].Value.ToString() == string.Empty))
						{
							cell_empty = true;
							break;
						}
						if (mod.ContainsKey((byte)row.Cells[0].Value))
						{
							duplicate_key = true;
							break;
						}
						if (mod.ContainsValue((byte)row.Cells[1].Value))
						{
							duplicate_val = true;
							break;
						}
						// finally
						mod.Add((byte)row.Cells[0].Value, (byte)row.Cells[1].Value);
					}
					current_row_idx++;
				}
				if (cell_empty == true)
				{
					MessageBox.Show("You left a cell empty.", "Error");
					this.dgvTable.ClearSelection();
					this.dgvTable.Rows[current_row_idx].Selected = true;
				}
				else if (duplicate_key == true)
				{
					MessageBox.Show("Keys should be unique. Please review and correct.", "Error");
					this.dgvTable.ClearSelection();
					this.dgvTable.Rows[current_row_idx].Selected = true;
				}
				else if (duplicate_val == true)
				{
					MessageBox.Show("Values should be unique. Please review and correct.", "Error");
					this.dgvTable.ClearSelection();
					this.dgvTable.Rows[current_row_idx].Selected = true;
				} else {
					this.ct_edit.Table = mod;
					this.ct_edit.Name = this.tbName.Text;
					this.ct_edit.Description = this.tbDescription.Text;
					if (this.ct_edit.isValid())
					{
						if (this.CreateNew == true)
						{
							string f;
							SaveFileDialog saveTableAs = new SaveFileDialog();
							
							saveTableAs.Title = "Save As...";
							saveTableAs.InitialDirectory = Application.StartupPath + @"\" + this.ConfigDir;
							saveTableAs.Filter = "JSON-Encoded Text Files (*.cfg)|*.cfg";
							saveTableAs.FilterIndex = 1;
							saveTableAs.RestoreDirectory = true;
							
							if(saveTableAs.ShowDialog() == DialogResult.OK)
							{
								f = saveTableAs.FileName;
								this.ct_edit.SaveAs(f);
								this.DialogResult = DialogResult.OK;
								//this.Close();
							}
						} else { // editing existing ConversionTable
							this.ct_edit.Save();
							this.DialogResult = DialogResult.OK;
							//this.Close();
						}
					}
					else
					{
						string errorText = "The ConversionTable is invalid:\n\n";
						if (!this.ct_edit.isValid()) errorText += this.ct_edit.ErrorText;
						MessageBox.Show(errorText, "Error");
					}
				}
				
				
			} catch (Exception ex) {
				MessageBox.Show("An error has occured trying to save ConversionTable.\nOriginal error: " + ex.Message);
			}
			
		}
	}
}
